package cn.iocoder.yudao.framework.swagger;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.crypto.annotation.ApiRequestDecrypt;
import cn.iocoder.yudao.framework.crypto.annotation.ApiResponseEncrypt;
import io.swagger.v3.oas.models.Operation;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  权限、接口加解密等
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @link <a href="https://gitee.com/lab1024/smart-admin/blob/master/smart-admin-api-java17-springboot3/sa-base/src/main/java/net/lab1024/sa/base/common/swagger/SmartOperationCustomizer.java">SmartOperationCustomizer.java</a>
 * @author 1024创新实验室-主任:卓大
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/04/03
 */
@Component
public class SmartOperationCustomizer implements OperationCustomizer {

    @Override
    public Operation customize(Operation operation, HandlerMethod handlerMethod) {
        List<String> list = new ArrayList<>();
        list.add(getPermission(handlerMethod));
        list.add(getCrypto(handlerMethod));
        operation.setDescription(StrUtil.join("<br/>", list.stream().filter(StrUtil::isNotBlank).toList()));
        return operation;
    }

    private String getPermission(HandlerMethod handlerMethod) {
        PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
        if (preAuthorize != null) {
            return "<font style=\"color:red\" class=\"light-red\">权限校验：</font><br/>" +
                   preAuthorize.value();
        }
        return "";
    }

    private String getCrypto(HandlerMethod handlerMethod) {
        boolean decrypt = false;
        boolean encrypt = false;
        if (handlerMethod.getMethodAnnotation(ApiRequestDecrypt.class) != null ||
            handlerMethod.getBeanType().getAnnotation(ApiRequestDecrypt.class) != null) {
            decrypt = true;
        }
        if (handlerMethod.getMethodAnnotation(ApiResponseEncrypt.class) != null ||
            handlerMethod.getBeanType().getAnnotation(ApiResponseEncrypt.class) != null) {
            encrypt = true;
        }
        if (decrypt || encrypt) {
            StringBuilder builder = new StringBuilder();
            builder.append("<font style=\"color:red\" class=\"light-red\">接口安全：");
            if (decrypt) {
                builder.append("【请求参数解密】");
            }
            if (encrypt) {
                builder.append("【响应结果加密】");
            }
            builder.append("</font>");
            return builder.toString();
        }
        return "";
    }

}
